package com.qf.controller.popularize;

import com.alibaba.druid.util.StringUtils;
import com.qf.pojo.DtsTopic;
import com.qf.service.DtsTopicService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.controller.popularize
 * @Description:
 * @Date 2022/10/21 19:52
 */
@RestController
@RequestMapping("/admin/topic")
public class AdminTopicController {

    @Autowired
    DtsTopicService topicServicre;

    @GetMapping("/list")
    public Object list(@RequestParam(value = "page",required = false,defaultValue = "1") Integer page ,
                       @RequestParam(value = "limit",required = false,defaultValue = "20") Integer limit,
                       @RequestParam(value = "sort",required = false,defaultValue = "add_time") String sort,
                       @RequestParam(value = "order",required = false,defaultValue = "desc") String order,
                       String title,String subtitle){

        Map<String, Object> data = topicServicre.selectPage(page,limit,sort,order,title,subtitle);
        return ResponseUtil.ok(data);
    }

    @PostMapping("/create")
    public Object create(@RequestBody DtsTopic topic){
        Object result = checkDtsTopic(topic);
        if (result!=null){
            return result;
        }
        topic.setAddTime(new Date());
        topic.setDeleted(false);
        topic.setUpdateTime(new Date());
        topicServicre.insert(topic);
        return ResponseUtil.ok(topic);
    }

    private Object checkDtsTopic(DtsTopic topic) {
        if (StringUtils.isEmpty(topic.getContent()) || StringUtils.isEmpty(topic.getSubtitle())){
            return ResponseUtil.fail(-1,"专题标题和子标签不能为空");
        }
        if (topic.getPrice()==null){
            return ResponseUtil.fail(-1,"专题低价不能为空");
        }

        return null;
    }

    @PostMapping("/update")
    public Object update(@RequestBody DtsTopic topic){
        topic.setUpdateTime(new Date());
        topicServicre.update(topic);
        return ResponseUtil.ok(topic);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody DtsTopic topic){
        topicServicre.delete(topic);
        return ResponseUtil.ok();
    }
}
